﻿using KZ.Express.Presenter;
using KZ.Express.Resource;
using KZ.Utilities;
using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;

namespace KZ.Express.Order.Order
{
    public partial class StatisticView : FormBase, IStatisticView
    {
        #region Private Variables

        private int _supplierID, _carrierID;
        private Dictionary<string, DataTable> _tables;
        private Dictionary<string, DataGridView> _dataGrids;
        private Dictionary<string, BindingSource> _bindingSource;
        private Dictionary<string, bool> _isLoad;
        private Dictionary<string, string> _orderBy;
        private Dictionary<string, string> _orderDirection;
        private new StatisticPresenter _presenter;

        #endregion Private Variables

        #region Private Methods

        private void StatisticView_Load(object sender, EventArgs e)
        {
            _tables = new Dictionary<string, DataTable>();
            _dataGrids = new Dictionary<string, DataGridView>();
            _bindingSource = new Dictionary<string, BindingSource>();
            _isLoad = new Dictionary<string, bool>();
            _orderBy = new Dictionary<string, string>();
            _orderDirection = new Dictionary<string, string>();
            dtpFrom.Value = DateTime.Today.GetFirstDayOfMonth();
            dtpTo.Value = DateTime.Today.GetLastDayOfMonth();

            LoadSupplierCarrier();
        }

        private void tbcOrder_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (!_isLoad[tbcOrder.SelectedTab.Name])
                {
                    string[] tmp = tbcOrder.SelectedTab.Name.Split('_');
                    if (tmp.Length == 2)
                    {
                        _supplierID = Utility.IntParse(tmp[0]);
                        _carrierID = Utility.IntParse(tmp[1]);
                    }
                    else
                        _supplierID = _carrierID = 0;

                    _presenter.LoadDataTable();
                }
            }
            catch (BusinessLogicException ex)
            {
                SetMessage(ex.Message, false);
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            foreach (KeyValuePair<string, DataGridView> item in _dataGrids)
                _isLoad[item.Key] = false;

            tbcOrder_SelectedIndexChanged(tbcOrder, null);
        }

        protected override void LoadData()
        {
        }

        private void LoadSupplierCarrier()
        {
            try
            {
                _presenter.LoadSupplierCarrier();
            }
            catch (BusinessLogicException ex)
            {
                SetMessage(ex.Message, false);
            }
        }

        private DataTable CreateDataTable()
        {
            DataTable dt = new DataTable();

            dt.Columns.Add("OrderID", typeof(int));
            dt.Columns.Add("Number", typeof(int));
            dt.Columns.Add("OrderDate", typeof(string));
            dt.Columns["OrderDate"].AllowDBNull = true;
            dt.Columns.Add("OrderNumber", typeof(string));
            dt.Columns["OrderNumber"].AllowDBNull = true;
            dt.Columns.Add("CustomerID", typeof(int));
            dt.Columns["CustomerID"].AllowDBNull = true;
            dt.Columns.Add("CountryID", typeof(int));
            dt.Columns["CountryID"].AllowDBNull = true;
            dt.Columns.Add("Type", typeof(string));
            dt.Columns["Type"].AllowDBNull = true;
            dt.Columns.Add("Weight", typeof(decimal));
            dt.Columns["Weight"].AllowDBNull = true;
            dt.Columns.Add("CustomerCode", typeof(string));
            dt.Columns["CustomerCode"].AllowDBNull = true;
            dt.Columns.Add("CustomerGroupName", typeof(string));
            dt.Columns["CustomerGroupName"].AllowDBNull = true;
            dt.Columns.Add("StandardPrice", typeof(decimal));
            dt.Columns["StandardPrice"].AllowDBNull = true;
            dt.Columns.Add("ListPrice", typeof(decimal));
            dt.Columns["ListPrice"].AllowDBNull = true;

            return dt;
        }

        private DataGridView CreateDataGridView(string key, BindingSource bds)
        {
            DataGridView dtg = new DataGridView();
            dtg.CellClick += dtg_CellClick;

            int index;
            dtg.AutoGenerateColumns = false;
            dtg.Dock = DockStyle.Fill;
            dtg.RowHeadersVisible = false;
            dtg.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dtg.DataSource = bds;
            Global.SetDoubleBuffered(dtg);

            dtg.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dtg.ReadOnly = true;
            dtg.AllowUserToResizeRows = false;
            dtg.AllowUserToDeleteRows = false;
            dtg.AllowUserToAddRows = false;

            index = dtg.Columns.Add("colNumber_" + key, "#");
            dtg.Columns[index].Width = 40;
            dtg.Columns[index].ReadOnly = true;
            dtg.Columns[index].SortMode = DataGridViewColumnSortMode.NotSortable;
            dtg.Columns[index].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dtg.Columns[index].DataPropertyName = "Number";

            index = dtg.Columns.Add("colCustomerCode_" + key, "Mã khách hàng");
            dtg.Columns[index].DataPropertyName = "Customercode";
            dtg.Columns[index].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

            index = dtg.Columns.Add("colCustomerName_" + key, "Tên khách hàng");
            dtg.Columns[index].DataPropertyName = "CustomerName";
            dtg.Columns[index].Width = 300;
            dtg.Columns[index].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

            index = dtg.Columns.Add("colCustomerGroupName_" + key, "Nhóm KH");
            dtg.Columns[index].ReadOnly = true;
            dtg.Columns[index].DataPropertyName = "CustomerGroupName";
            dtg.Columns[index].Width = 80;
            dtg.Columns[index].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

            index = dtg.Columns.Add("colTotalStandardAmount_" + key, "Tổng tiền gốc (USD)");
            dtg.Columns[index].Width = 110;
            dtg.Columns[index].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dtg.Columns[index].DefaultCellStyle.Format = "N2";
            dtg.Columns[index].DataPropertyName = "TotalStandardAmount";

            index = dtg.Columns.Add("colTotalListAmount_" + key, "Tổng tiền bán (USD)");
            dtg.Columns[index].Width = 110;
            dtg.Columns[index].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dtg.Columns[index].DefaultCellStyle.Format = "N2";
            dtg.Columns[index].DataPropertyName = "TotalListAmount";

            index = dtg.Columns.Add("colVNDListOptional_" + key, "Tổng đc giá bán tăng (VND)");
            dtg.Columns[index].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dtg.Columns[index].DefaultCellStyle.Format = "N0";
            dtg.Columns[index].DataPropertyName = "VNDTotalListOptionalIncrease";

            index = dtg.Columns.Add("colVNDListOptional_" + key, "tổng đc giá bán giảm (VND)");
            dtg.Columns[index].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dtg.Columns[index].DefaultCellStyle.Format = "N0";
            dtg.Columns[index].DataPropertyName = "VNDTotalListOptionalDecrease";

            index = dtg.Columns.Add("colVNDTotalStandardAmount_" + key, "Tổng tiền gốc (VND)");
            dtg.Columns[index].Width = 150;
            dtg.Columns[index].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dtg.Columns[index].DefaultCellStyle.Format = "N0";
            dtg.Columns[index].DataPropertyName = "VNDTotalStandardAmount";

            index = dtg.Columns.Add("colVNDTotalListAmount_" + key, "Tổng tiền bán (VND)");
            dtg.Columns[index].Width = 150;
            dtg.Columns[index].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dtg.Columns[index].DefaultCellStyle.Format = "N0";
            dtg.Columns[index].DataPropertyName = "VNDTotalListAmount";

            index = dtg.Columns.Add("colCost_" + key, "Tổng chi phí (VND)");
            dtg.Columns[index].Width = 150;
            dtg.Columns[index].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dtg.Columns[index].DefaultCellStyle.Format = "N0";
            dtg.Columns[index].DataPropertyName = "TotalCost";

            index = dtg.Columns.Add("colDifference_" + key, "Chênh lệch (VND)");
            dtg.Columns[index].Width = 150;
            dtg.Columns[index].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dtg.Columns[index].DefaultCellStyle.Format = "N0;(N0);0";
            dtg.Columns[index].DataPropertyName = "Difference";

            index = dtg.Columns.Add("colTemp_" + key, String.Empty);
            dtg.Columns[index].ReadOnly = true;
            dtg.Columns[index].SortMode = DataGridViewColumnSortMode.NotSortable;
            dtg.Columns[index].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

            return dtg;
        }

        private void dtg_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex != -1 && e.RowIndex != -1)
            {
                MainView mainView = Application.OpenForms["MainView"] as MainView;
                OrderListView orderView = Application.OpenForms["OrderListView"] as OrderListView;
                mainView.OpenTab(orderView);
                mainView.HandleAction(ActionName.List);

                orderView.From = dtpFrom.Value;
                orderView.To = dtpTo.Value;
                orderView.SelectedTab(tbcOrder.SelectedIndex);
            }
        }

        #endregion Private Methods

        #region Constructors

        public StatisticView()
        {
            InitializeComponent();
            base.Action = ActionName.DisableMenu;
            base._presenter = _presenter = new StatisticPresenter(this);

            btnSearch.Click += btnViewAll_Click;
        }

        #endregion Constructors

        #region Public Properties

        [Search]
        public override string OrderBy
        {
            get { return _orderBy[tbcOrder.SelectedTab.Name]; }
            set { _orderBy[tbcOrder.SelectedTab.Name] = value; }
        }

        [Search]
        public override string OrderDirection
        {
            get { return _orderDirection[tbcOrder.SelectedTab.Name]; }
            set { _orderDirection[tbcOrder.SelectedTab.Name] = value; }
        }

        [Search]
        public int SupplierID
        {
            get { return _supplierID; }
        }

        [Search]
        public int CarrierID
        {
            get { return _carrierID; }
        }

        [Search]
        public DateTime From
        {
            get { return dtpFrom.Value; }
        }

        [Search]
        public DateTime To
        {
            get { return dtpTo.Value; }
        }

        public override DataTable Table
        {
            get { return _bindingSource[tbcOrder.SelectedTab.Name].DataSource as DataTable; }
            set
            {
                DataTable dt = value;
                if (!dt.Columns.Contains("Number"))
                {
                    DataColumn column = new DataColumn("Number", typeof(int));
                    column.ReadOnly = false;
                    dt.Columns.Add(column);
                }

                Global.GenerateNumber(ref dt);
                _tables[tbcOrder.SelectedTab.Name] = value;
                _bindingSource[tbcOrder.SelectedTab.Name].DataSource = null;
                _bindingSource[tbcOrder.SelectedTab.Name].DataSource = value;
            }
        }

        public DataTable SupplierCarrier
        {
            set
            {
                string key;
                DataTable dt;
                BindingSource bds;
                DataGridView dtg;
                TabPage tbp;
                foreach (DataRow row in value.Rows)
                {
                    key = row["PartnerID"] + "_" + row["CarrierID"];
                    if (!_dataGrids.ContainsKey(key))
                    {
                        dt = CreateDataTable();
                        bds = new BindingSource();
                        bds.DataSource = dt;

                        dtg = CreateDataGridView(key, bds);

                        _tables.Add(key, dt);
                        _dataGrids.Add(key, dtg);
                        _bindingSource.Add(key, bds);
                        _isLoad.Add(key, false);
                        _orderBy.Add(key, "OrderDate");
                        _orderDirection.Add(key, "ASC");

                        tbp = new TabPage(Utility.StringParse(row["PartnerName"]));
                        tbp.Name = key;
                        tbp.Controls.Add(dtg);

                        tbcOrder.TabPages.Add(tbp);
                    }
                }

                //// create datagridview summary
                key = "Summary";
                dt = CreateDataTable();
                bds = new BindingSource();
                bds.DataSource = dt;
                dtg = CreateDataGridView("Summary", bds);

                _tables.Add(key, dt);
                _dataGrids.Add(key, dtg);
                _bindingSource.Add(key, bds);
                _isLoad.Add(key, false);
                _orderBy.Add(key, "OrderDate");
                _orderDirection.Add(key, "ASC");

                tbp = new TabPage("Tổng kết");
                tbp.Name = key;
                tbp.Controls.Add(dtg);

                tbcOrder.TabPages.Add(tbp);

                tbcOrder_SelectedIndexChanged(tbcOrder, null);
            }
        }

        #endregion Public Properties
    }
}